package com.txw.javaCore.server.service;

import com.google.common.collect.Maps;
import com.txw.javaCore.api.enums.Constant;
import com.txw.javaCore.model.entity.RedisBlogData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @PROJECT_NAME: JavaCoreB2
 * @DESCRIPTION: 指标数据统计-已点赞、已收藏、已关注、已转发、评论总数 缓存
 * @Author: 涂玄武
 * @DATE: 2021/3/3 13:38
 */
@Service
@Slf4j
public class RedisBlogService implements CommandLineRunner {

    @Autowired
    private RedisTemplate redisTemplate;

    private HashOperations<String, String, Integer> blogCacheHash;

    private HashOperations<String, String, Integer> concernCacheHash;

    private HashOperations<String, String, Integer> commentCacheHash;

    //系统初始化加载时实现对象实例化-开发经验
    @Override
    public void run(String... args) throws Exception {
        blogCacheHash = redisTemplate.opsForHash();
        concernCacheHash = redisTemplate.opsForHash();
        commentCacheHash = redisTemplate.opsForHash();
    }

    /**
     * 缓存点赞、收藏、转发等指标数据
     * 针对用户对微博/朋友圈的操作
     *
     * @param data
     */
    public void cacheData(final RedisBlogData data) {
        try {
            if (data.getNeedCache()) {
                //点赞、转发、收藏-获取缓存中当前用户是否已点赞：0-点赞，1-未点赞
                //通过putIfAbsent()可以巧妙避免并发安全问题
                blogCacheHash.putIfAbsent(data.getCacheTypeKey() + data.getBlogId(), data.getUserId().toString(), 1);
                log.info("打印hash值：" + String.valueOf(blogCacheHash.get(data.getCacheTypeKey() + data.getBlogId(), String.valueOf(data.getUserId()))));
            } else {
                //取消点赞、取消转发、取消收藏
                blogCacheHash.delete(data.getCacheTypeKey() + data.getBlogId(), data.getUserId().toString());
            }

        } catch (Exception e) {
            log.error("朋友圈/微博点赞-收藏-转发统计数据-发生异常：{}", data, e);
        }
    }

    /**
     * 关注：针对用户对微博/朋友圈的作者（UP主）
     *
     * @param concernUId   关注者
     * @param concernBeUId 被关注者
     * @param needCache    是否需要缓存
     */
    public void cacheConcern(final Integer concernUId, final Integer concernBeUId, final Boolean needCache) {
        try {
            if (needCache) {
                concernCacheHash.putIfAbsent(Constant.KeyConcern + concernUId, concernBeUId.toString(), 1);
            } else {
                concernCacheHash.delete(Constant.KeyConcern + concernUId, concernBeUId.toString());
            }
        } catch (Exception e) {
            log.error("朋友圈/微博关注统计数据-发生异常：concernUId={},concernBeUId={},needCache={} ", concernUId, concernBeUId, needCache, e);
        }
    }

    //评论总数：针对微博/朋友圈而言
    public void cacheDataComment(final Integer blogId, final Integer total) {
        try {
            commentCacheHash.put(Constant.KeyComment, blogId.toString(), total);
        } catch (Exception e) {
            log.error("朋友圈/微博评论统计数据-发生异常：blogId={},total={} ", blogId, total, e);
        }
    }

    /**
     * 获取缓存中的统计数据：点赞/收藏/转发/关注/评论总数
     * @param blogId
     * @param currUserId
     * @param beUserId
     * @return
     */
    public Map<String, Object> getStaticData(final Integer blogId, final Long currUserId, final Long beUserId) {
        HashMap<String, Object> otherMap = Maps.newHashMap();

        try {
            if (!Objects.isNull(currUserId)) {
                Integer hasPraise = blogCacheHash.get(Constant.KeyPraise + blogId, currUserId.toString());
                Integer hasCollect = blogCacheHash.get(Constant.KeyCollect + blogId, currUserId.toString());
                Integer hasForward = blogCacheHash.get(Constant.KeyForward + blogId, currUserId.toString());
                Integer hashConcern = concernCacheHash.get(Constant.KeyConcern + currUserId, beUserId.toString());
                Integer commentTotal = commentCacheHash.get(Constant.KeyComment, blogId.toString());

                otherMap.put("hasConcern", (!Objects.isNull(hashConcern) && hashConcern > 0) ? 1 : 0);
                otherMap.put("hasPraise", (!Objects.isNull(hasPraise) && hasPraise > 0) ? 1 : 0);
                otherMap.put("hasCollect", (!Objects.isNull(hasCollect) && hasCollect > 0) ? 1 : 0);
                otherMap.put("hasForward", (!Objects.isNull(hasForward) && hasForward > 0) ? 1 : 0);
                otherMap.put("commentTotal", (!Objects.isNull(commentTotal) && commentTotal >= 0) ? commentTotal : 0);
            }
        } catch (Exception e) {
            log.error("获取缓存中的统计数据：点赞/收藏/转发/关注/评论总数-发生异常：", e);
        }
        return otherMap;
    }
}
